package services

import (
	"encoding/json"
	"fmt"
	"log"
	"time"
)

type ReceiveMessage struct {
	Type    string `json:"type"`
	Payload string `json:"payload"`
}

type SendMessage struct {
	Type    string      `json:"type"`
	Payload string      `json:"payload"`
	Data    interface{} `json:"data"`   // 消息内容
	SentAt  int64       `json:"sentAt"` // 发送时间戳
}

func HandleReceiveMessage(message []byte) (string, error) {
	// 解析 JSON
	var msg ReceiveMessage
	if err := json.Unmarshal(message, &msg); err != nil {
		return "", fmt.Errorf("解析 JSON 失败: %T", err)
	}
	// 根据消息类型处理
	switch msg.Type {
	case "trend":
		data, _ := GetTrend()
		return buildJSONMessage(msg.Type, msg.Payload, data), nil
	case "horizontal-bar":
		data, _ := GetAmount()
		return buildJSONMessage(msg.Type, msg.Payload, data), nil
	case "calendar":
		data, _ := GetCalendar()
		return buildJSONMessage(msg.Type, msg.Payload, data), nil
	default:
		return "", fmt.Errorf("未知消息类型: %s", msg.Type)
	}
}

// 构建JSON消息
func buildJSONMessage(msgType, payload string, data interface{}) string {
	msg := SendMessage{
		Type:    msgType,
		Payload: payload,
		Data:    data,
		SentAt:  time.Now().Unix(),
	}

	jsonData, err := json.Marshal(msg)
	if err != nil {
		log.Printf("JSON编码失败: %v", err)
		return fmt.Sprintf(`{"type":"error","data":"json encode error"}`)
	}
	return string(jsonData)
}
